/**
 * @Author: Your name
 * @Date:   2024-03-15 16:18:59
 * @Last Modified by:   Your name
 * @Last Modified time: 2024-03-15 16:44:41
 */
import React, { Component } from 'react';
import ChatMessage from './ChatMessage';

class ChatWindow extends Component {
  state = {
    messages: [],
    newMessage: '',
  };

  // 模拟接收新消息
  componentDidMount() {
    // 假设每隔5秒收到一条新消息
    setInterval(() => {
      const { messages } = this.state;
      const receivedMessage = {
        content: '这是一条新消息',
        from: 'Other',
      };
      this.setState({
        messages: [...messages, receivedMessage],
      });
    }, 5000);
  }

  sendMessage = () => {
    const { newMessage, messages } = this.state;
    if (newMessage.trim() !== '') {
      this.setState({
        messages: [...messages, { content: newMessage, from: 'Me' }],
        newMessage: '',
      });
      // 在这里可以调用发送消息的函数，将消息发送到服务器
    }
  };

  render() {
    const { messages, newMessage } = this.state;

    return (
      <div className="h-96 flex flex-col border">
        <div className="overflow-auto flex-grow">
          {messages.map((message, index) => (
            <ChatMessage key={index} message={message} />
          ))}
        </div>
        <div className="flex items-center">
          <input
            type="text"
            value={newMessage}
            onChange={(e) => this.setState({ newMessage: e.target.value })}
            className="flex-grow px-4 py-2 border border-gray-300 rounded-l-md focus:outline-none"
            placeholder="输入消息..."
          />
          <button
            onClick={this.sendMessage}
            className="bg-blue-500 text-white px-4 py-2 rounded-r-md hover:bg-blue-600 focus:outline-none"
          >
            发送
          </button>
        </div>
      </div>
    );
  }
}

export default ChatWindow;
